<?php
/**
 * 体检预约
 *
 * User: kaikaic
 * Date: 2018/10/28
 * Time: 21:10
 */

namespace app\api\controller;

use app\api\service\ConsultantService;
use app\api\service\MainService;
use app\api\model\OrderModel;
use app\psy\controller\Order;
use app\psy\service\OrderService;
use controller\BasicApi;
use service\WechatService;
use think\Console;
use think\Db;

class Book extends BasicApi {
    /**
     * 首页
     */
    public function index() {
        $accountID = intval($this->getParams("uid"));           // 用户ID
        $consulantid = intval($this->getParams("consulantid"));           // 用户ID
        $orderDate = $this->getParams("order_date");              // 体检日期
        $order_between = $this->getParams("order_between");              // 体检日期
        $type = $this->getParams("type");
        $price= intval($this->getParams("price",0));  // ID
        $isread= intval($this->getParams("isread",0));  // ID
        if (!$accountID || !$consulantid || !$orderDate ) {
            $this->error("参数错误", 0);
        }

        $params['account_id'] = $accountID;
        $params['consultant_id'] = $consulantid;
        $params['order_time'] = $orderDate;
        $params['price'] = $price;
        $params['order_periods'] = $order_between;
        $params['type'] = $type;
        $params['isread'] = $isread;
        $orderModel = new OrderModel();
        $flag = $orderModel->isOrderExist($params);
        if ($flag) {
            $this->error("已经有当天的预约", 0);
        }
        $params['order_status'] = 1;
        $params['pay_status'] = 1;
        $params['create_time'] = time();
        $result = $orderModel->createOrder($params);

        if ($result) {
            $res = $orderModel->orderInfo($result);
            $this->success('下订单成功',$res);
        }else {
            $this->error("预约失败, 稍候重试", 0);
        }

    }

    private function isDate($data) {
        if (date("Y-m-d", strtotime($data)) == $data) {
            return true;
        }else {
            return false;
        }
    }
    public function ordertips(){
        $sql = "select a1.*,a2.mobile as umobile,a3.name as consultname,a3.account_id as cid,a4.name as typename from psy_order a1
left join account a2 on a1.account_id = a2.id
left join psy_consultant a3 on a1.consultant_id = a3.id
left join system_category a4 on a1.type = a4.id
                where a1.order_status = 2 
                and a1.pay_status = 2 
                and TIMESTAMPDIFF(HOUR,NOW(),a1.order_time) <=48
                AND TIMESTAMPDIFF(HOUR,NOW(),a1.order_time) >24";
        $res = Db::query($sql);
        foreach ($res as $key=>&$item){

            $title1 = "您的预约：".$item['order_time']."，".$item['typename']."心理咨询，请提前做好准备。 【九州心理咨询】";

            $sql1 = "select mobile from  account 
                where id=".$item['cid'];
            $res1 = Db::query($sql1);
            $sendphone1 = $res1[0]['mobile'];

            if($item['type_txt']=='视频'){

                $title2 = "您的视频咨询预约，请于".$item['order_time']." ".$item['order_periods']."，在安静无打扰、网络效果好的环境进行咨询。";

            }else{
                $title2  = "您的当面咨询预约，请于".$item['order_time']." ".$item['order_periods']."，准时到达预约地点（".$item['comment']."），迟到或者逾期不到都不退费。【九州心理咨询】";
            }

            $sendphone2 = $item['umobile'];

            sendSms($sendphone1,$title1);
            sendSms($sendphone2,$title2);
        }
        print_r($res);
    }

    /*
    * 订单 - 微信支付
    * http://fri.game.com/index/order/wxpay?order_sn=460580141610194198&openId=oyWmc0p5tE7JHDlfN29xVT5sAyOM
    */
    public function wxpay()
    {
        $orderSN = $this->request->param('order_sn', 0);
        $openId = $this->request->param('openId', 0);
        $request = $this->request;
        $ip_address = $request->ip();
        $notifyurl = "https://".$_SERVER['HTTP_HOST']."/api/book/wxnotify";
        if ($orderSN && $openId) {
        } else {
            $this->error('非法操作！');
        }
        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if($orderInfo['order_time'] < date('Y-m-d')){
            $this->error('该预约时间已过期！');
        }
        elseif ($orderInfo['pay_status'] != 1) {
            $this->error('订单已支付！');
        } else {
            $return = WechatService::unifiedorder($openId, $orderSN, '九州心理咨询', $orderInfo['price'], $ip_address,$notifyurl);
            if (isset($return['return_code']) && $return['return_code'] == 'SUCCESS') {
                 $this->success('获取成功！', $return);
            } else {
                 $this->error('签名返还错误！', $return);
            }
        }
    }

    // 微信支付回调
    public function wxnotify()
    {

        $filename = "aa.txt";
        $fp = fopen($filename, 'a+');
        fwrite($fp, "success");
        $receipt = $_REQUEST;
        if ($receipt == null) {
            $receipt = file_get_contents("php://input");
            if ($receipt == null) {
                $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
            }
        }
        $receipt = WechatService::xmlToArray($receipt);
        fwrite($fp, var_export($receipt, true));
        fclose($fp);

//        $flag = WechatService::checkSign($receipt);
//        $flag = 1;
//        $receipt =  array (
//            'appid' => 'wx9be58386ffe592ca',
//            'attach' => 'XL20181229183730000000003801',
//            'bank_type' => 'CFT',
//            'cash_fee' => '1',
//            'fee_type' => 'CNY',
//            'is_subscribe' => 'N',
//            'mch_id' => '1521886831',
//            'nonce_str' => '8ko0dkpl455c0cmxt7zug1ayzcjs65nc',
//            'openid' => 'obz9W40-rA_xL3CnzqzxGbITIVRw',
//            'out_trade_no' => 'XL20181229183730000000003801',
//            'result_code' => 'SUCCESS',
//            'return_code' => 'SUCCESS',
//            'sign' => 'B4485D714212E046D7199674DE3255DE',
//            'time_end' => '20181229183816',
//            'total_fee' => '1',
//            'trade_type' => 'JSAPI',
//            'transaction_id' => '4200000234201812295136501609',
//        );
        $flag = WechatService::checkSign($receipt);
        if ($flag) {
            // 支付日志
            $res =   $order =  MainService::getOrderInfoByOrdersn($receipt['out_trade_no']);

            $logData['account_id'] = $order['account_id'];
            $logData['order_sn'] = $receipt['attach'];
            $logData['create_time'] = time();
            $logData['money'] = $receipt['total_fee'] / 100;
            $logData['transaction_id'] = $receipt['transaction_id'];
            $pay_id = Db::name("wechat_pay_notify")->insertGetId($logData);

            // 订单表状态
            $data['pay_status'] = 2;
            $data['order_status'] = 1;
            $data['update_time'] = time();
            $ups = Db::name("psy_order")->where("order_sn", $receipt['out_trade_no'])->update($data);

            // 支付状态
            $pay_s = Db::name("psy_order_pay")->where("pay_sn", $res['pay_sn'])->update(array('api_pay_state'=>1));

            //发送短信
            $msg = "有新预约：".$res['order_time']." ".$res['order_periods']."，".$res['consult']['name']."老师".$res['type_txt']."咨询。请尽快前往后台确认订单。 【九州心理咨询】";

            sendSms('18008451236',$msg);
            // 向第三方下单
//            $money =  $receipt['total_fee']/100;
//            $thirdData = array(
//                'orderId' => $order['order_sn'],
//                'pdtId' => $order_ticket['third_code'],
//                'num' => $order_ticket['num'],
//                'contactor' => $order_ticket['name'],
//                'cellphone' => $order_ticket['mobile'],
//                'money' => $money
//            );
//            $third = OrderService::createOrderThird($thirdData);
//            $fp = fopen($filename, 'a+');
//            fwrite($fp, "success3");
////            fwrite($fp, var_export($thirdData, true));
//            fclose($fp);
//            if ($third) {
//                Db::name("scenic_order_pay")->where("pay_sn", $receipt['out_trade_no'])->update(array('api_pay_code'=>$third['qrCode'],"api_pay_orderid"=>$third['orderId']));
//                $data['status_order'] = 3;
//                $ups = Db::name("ScenicOrder")->where("pay_sn", $receipt['out_trade_no'])->update($data);
                exit('SUCCESS');
//            } else {
//                exit('SUCCESS');
//            }
        }else{
            exit('SUCCESS');
        }
    }
    public function test(){
        $res =   $order =  MainService::getOrderInfoByOrdersn('XL20190521152113000000009701');
        print_r($res);
        //发送短信
        $msg = "有新预约：".$res['order_time']." ".$res['order_periods']."，".$res['consult']['name']."老师".$res['type_txt']."咨询。请尽快前往后台确认订单。【九州心理咨询】";

       print_r(sendSms('18273392280',$msg));
    }
    public function getconsultorderlist(){
        $page = $this->request->param('page',1)-1;
        $size = 6;
        $order_status = $this->request->param('order_status',0);
        $consult_id = $this->request->param('consult_id');
        $orderList = MainService::getOrderList($consult_id,$order_status,$page,$size,2);
        $this->success( '获取成功',$orderList);
    }
    public function getorderlist(){
        $page = $this->request->param('page',1)-1;
        $size = 6;
        $order_status = $this->request->param('order_status',0);
        $account_id = $this->request->param('uid');
        $orderList = MainService::getOrderList($account_id,$order_status,$page,$size,1);
        $this->success( '获取成功',$orderList);
    }
    public function cancelorder(){
        $orderSN = $this->request->param('order_sn', 0);

        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if ($orderInfo['order_status'] != 1) {
            $this->error('该订单不能取消');
        } else {
            $update['order_status'] = 10;
            $update['cancel_time'] = time();
            $staus =  MainService::cancelOrder($orderSN,$update);
            if($staus){
               $this->success('取消成功');
            }else{
               $this->error('取消失败');
            }
        }
    }
    public function orderdetail(){
        $orderSN = $this->request->param('order_sn', 0);

        $orderInfo = MainService::getOrderInfoByOrdersn($orderSN);
        if ($orderInfo) {
            $this->success('获取成功',$orderInfo);
        } else {
            $this->error('参数错误');
        }
    }
    public function changedate(){
        $ordersn = $this->request->param('order_sn', 0);
        $data['exam_date'] = $exam_date = $this->request->param('exam_date', 0);
        $data['update_time'] = time();
        $orderInfo = Db::name("exam_order")->where('order_sn',$ordersn)->update($data);
        if ($orderInfo) {
            $res['status'] = 2;
           Db::name("exam_group_member")->where('order_sn',$ordersn)->update($res);
            $this->success('预约成功',$orderInfo);
        } else {
            $this->error('参数错误');
        }
    }

    //发送消息模板
    public function smallWXmessage()
    {
        $data = $this->request->param();
//        $prepay_id = 'wx07144432523182a95edb1d674277613093';
//
//        $openid = 'o2ECm5LPCIQk6x-6AqBrTAwS2lds';
//        $order_sn = 'XL20190507112902000000008701';
        $order_sn = $this->request->param('order_sn') ;
        $openid =  $this->request->param('openid') ;
        $prepay_id =  $this->request->param('prepay_id');
        $res = OrderService::getInstance()->find($order_sn,'order_sn');
        $consult =array();
        if($res){
            $consult = ConsultantService::getInstance()->find($res['consultant_id']);
        }
        /*
         * qKrFnnwLB_QZOp80k_U2SQcIOmxJEm9K_Q2M4y2Y7oE复制
            标题
            订单支付成功通知
            关键词
            下单时间
            {{keyword1.DATA}}
            订单号码
            {{keyword2.DATA}}
            服务名称
            {{keyword3.DATA}}
            预约时间
            {{keyword4.DATA}}
            支付时间
            {{keyword5.DATA}}
            订单金额
            {{keyword6.DATA}}
         */
        $create_time  = date('Y-m-d H:i:s',$res['create_time']);
        $desv  = '预约'.$consult['name'].'心理咨询';
        $order_periods  = $res['order_time'].' '.$res['order_periods'];
        $update_time  = date('Y-m-d H:i:s',$res['update_time']);
        $price  = $res['price'];

        $datares['touser'] = $openid;
        $datares['template_id'] =  'jqPmR7cUGJBzVHsqjFGY3sSbVcq9zMFWmzQ72MpDNgM';
        $datares['page'] =  '/pages/ordetails/ordetails?order_sn='.$order_sn;
        $datares['form_id'] =  $prepay_id;
        $data2['keyword1']['value'] =$create_time;
        $data2['keyword2']['value'] = $desv;
        $data2['keyword3']['value'] = $order_sn;
        $data2['keyword4']['value'] = $order_periods;
        $data2['keyword5']['value'] = $update_time;
        $data2['keyword6']['value'] = $price;
        $datares['data'] = $data2;

        $datajson = json_encode($datares);
        print_r($datajson);

        $res = WechatService::sendmsg($datajson);
        return $res;
    }
}

